﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Common.Handle
{
    /// <summary>
    /// 封包处理特性
    /// </summary>
    public class PacketTypeAttribute : Attribute
    {
        public RecvPacketOpcode m_Head;
        public PacketTypeAttribute(RecvPacketOpcode recv)
        {
            m_Head = recv;
        }
    }


    public class PacketProcessor
    {

        /// <summary>
        /// 事件字典
        /// </summary>
        Dictionary<RecvPacketOpcode, MaplePacketHandler> m_Handlers = new Dictionary<RecvPacketOpcode, MaplePacketHandler>();


        ///// <summary>
        ///// 注册事件
        ///// </summary>
        ///// <param name="code"></param>
        ///// <param name="handle"></param>
        //public void registerHandler(RecvPacketOpcode code, MaplePacketHandler handle)
        //{
        //    this.m_Handlers.Add(code, handle);
        //}


        ///// <summary>
        ///// 获取事件
        ///// </summary>
        ///// <param name="code"></param>
        ///// <returns></returns>
        public MaplePacketHandler GetHandler(RecvPacketOpcode code)
        {
            if (m_Handlers.ContainsKey(code))
            {
                return m_Handlers[code];
            }

            return null;
        }


        public PacketProcessor()
        {
            //获取该程序下全部命名空间
            var classes = Assembly.GetExecutingAssembly().GetTypes();
            foreach (var item in classes)
            {
                //获取各类特性
                foreach (Attribute attr in Attribute.GetCustomAttributes(item))
                {
                    if (attr is PacketTypeAttribute)
                    {
                        RecvPacketOpcode code = (attr as PacketTypeAttribute).m_Head;
                        Type x = System.Type.GetType(item.MakePointerType().FullName.Split('*')[0]);//.GetType();
                        object handler = Activator.CreateInstance(x);
                        Console.WriteLine("处理事件注册:{0}", code);
                        m_Handlers.Add(code, (MaplePacketHandler)handler);
                    }
                }
            }
        }


    }
}
